package com.brother.template.inflxudb.dao;

import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xjw on 2018/3/29.
 */
@Repository
public class InfluxdbBaseDao {

    private Logger log = LoggerFactory.getLogger(InfluxdbBaseDao.class);

    public void insert(String url, String dbName, List<Point> points) {
        try {
//            influxDB = InfluxDBFactory.connect(url);
            InfluxDB influxDB = MyInfluxDBUtil.getInfluxDB(url);
            if (!influxDB.databaseExists(dbName)) {
                log.info("create " + dbName);
                influxDB.createDatabase(dbName);
                log.info("version === " + influxDB.version());
            }
            influxDB.setDatabase(dbName);
            String rp = InfluxdbUtil.defaultRetentionPolicy(influxDB.version());
            influxDB.setRetentionPolicy(rp);

            BatchPoints batchPoints = BatchPoints.database(dbName).retentionPolicy(rp).build();

            if (!points.isEmpty()) {
                for (Point p : points) {
                    batchPoints.point(p);
                }
                influxDB.write(batchPoints);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }


    }

    public void deleteDatabase(String dbName, String url) {
        InfluxDB influxDB = InfluxDBFactory.connect(url);

        influxDB.deleteDatabase(dbName);
    }

    public static class MyInfluxDBUtil {

        private static final Object lockObj = new Object();
        private static volatile Map<String, ThreadLocal<InfluxDB>> influxDBMap = new HashMap<>();

        private MyInfluxDBUtil() {

        }

        public static InfluxDB getInfluxDB(String url) {
            ThreadLocal<InfluxDB> influxDB = influxDBMap.get(url);
            if (influxDB == null) {
                synchronized (MyInfluxDBUtil.class) {
                    if (influxDB == null) {
                        influxDB = new ThreadLocal<InfluxDB>() {
                            @Override
                            protected InfluxDB initialValue() {
                                return InfluxDBFactory.connect(url);
                            }
                        };
                        influxDBMap.put(url, influxDB);
                    }
                }
            }
            return influxDB.get();
        }
    }


}
